<template>
	<u-popup :show="showPopup" @close="close">
		<view class="specsPop padding30" v-if="pageData">
			<view class="d-flex">
				<image class="img bor_radius_4 m-right20 f-shrink-0" :src="$imgUrls(currentSpecs.img || pageData.img)"
					mode="aspectFill"></image>
				<view class="d-flex f-column j-sb">
					<view class="p-right40 size28">{{ pageData.name }}</view>
					<view>
						<text class="color_FOD size32 bold">￥</text>
						<text class="color_FOD size40 bold">{{ currentSpecs.price || pageData.price }}</text>
					</view>
				</view>
			</view>
			<view class="scroll-y" style="min-height: 300rpx; max-height: 50vh;">
				<view v-for="(item, index) in specsList" :key="index">
					<view class="size28 color_33 bold m-top30 m-bot20">{{ item.title }}</view>
					<view v-if="item.list">
						<view class="specsItm d-inline-block color_66 bor_radius_30s"
							:class="{ active: specs_ids[index] == itm.specs_id, color_cc: !itm.state }"
							@click="handleSpecs(index, itm.state, itm.specs_id)" v-for="(itm, idx) in item.list"
							:key="idx">{{ itm.title }}</view>
					</view>
				</view>
			</view>
			<view class="d-flex j-sb a-center">
				<view class="size28 color_33 bold m-top30 m-bot40">数量</view>
				<view><u-number-box v-model="v_input" integer :max="stock" @overlimit="overlimit"></u-number-box></view>
			</view>
			<view class="row j-sb white">
				<view class="btn flexac bgFFA size28 m-right30" @click="handleSubmit(1)" v-if="pageData.join_cart == 1">
					加入购物车</view>
				<view class="btn flexac bgFF4B size28" @click="handleSubmit(2)">立即购买</view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		props: ['showPopup', 'pageData'],

		data() {
			return {
				specsList: [], // 规格列表
				specsCopy: '', // 原始数据字符串
				specs_ids: [],
				stock: '', // 当前规格组合的库存或总库存
				currentSpecs: '',
				v_input: 1 // 计数器
			}
		},
		watch: {
			'pageData.goods_id': {
				deep: true,
				handler(newVal) {
					this.init()
					if (!newVal) return
					this.stock = this.pageData.stock
					this.getSpecs()
				}
			}
		},
		methods: {
			getSpecs() {
				this.$http.post({
					url: '/publicPlugins/getGoodsSpcInfo',
					data: {
						goods_id: this.pageData.goods_id,
						shop_id: this.pageData.store_id || ''
					}
				}).then(res => {
					if (res.code != 100) return this.$Toast(res.msg)
					let getGoodsSpecs = res.data
					if (!getGoodsSpecs) return
					this.pageData.getGoodsSpecs = getGoodsSpecs
					let {
						specsList,
						specsPrice
					} = getGoodsSpecs
					if (specsList && specsPrice) {
						this.specsList = specsList
						this.specsCopy = JSON.stringify(this.specsList)
						let first = specsPrice.find(item => item.stock > 0) // 接口返回的specs_ids默认从小到大排序
						if (first) {
							specsList.forEach((item, index) => {
								// 强制按照规格类别排序且个数一致
								let obj = item.list.find(itm => first.specs_ids.includes(itm.specs_id))
								this.specs_ids[index] = obj ? obj.specs_id : ''
							})
							this.stock = first.stock
							this.currentSpecs = first
						}
					}
				})
			},
			close() {
				this.$emit('close')
			},
			init() {
				this.specsList = []
				this.specs_ids = []
				this.currentSpecs = ''
				this.v_input = 1
			},
			overlimit(type) {
				if (type == 'plus') {
					this.$Toast('库存不足')
				}
			},
			handleSpecs(index, itmState, id) {
				// 类别索引,规格状态,规格id
				if (!itmState) return // 禁选
				if (this.specs_ids[index] == id) return // 已选

				let {
					specsPrice
				} = this.pageData.getGoodsSpecs
				this.specs_ids[index] = id // 非响应式
				let empty = this.specs_ids.filter((item) => !item)

				if (!empty.length) {
					// 已选完
					let up = this.specs_ids.slice().sort((a, b) => a - b) // 创建副本再排序不影响原数组
					let current = specsPrice.find((item) => item.specs_ids == up.toString())

					if (current) {
						this.specs_ids = [...this.specs_ids] // 更新视图
						this.stock = current.stock
						this.currentSpecs = current
						// 当前所选类别有无禁选规格，无则还原list
						let result = this.specsList[index].list.find((item) => !item.state)
						if (!result) this.specsList = JSON.parse(this.specsCopy)
					} else {
						// 没找到为undefined
						this.specs_ids = this.specs_ids.map((item) => (item == id ? id : '')) // 只保留当前所选规格，其余类别规格id清空
					}
				} else if (empty.length == 1) {
					// 仅剩一个类别未选，需判断该类别有无禁选规格
					this.specs_ids = [...this.specs_ids]
					// 未选类别索引
					let i = this.specs_ids.findIndex((item) => !item)
					this.specsList[i].list.forEach((item) => {
						let arr = JSON.parse(JSON.stringify(this.specs_ids))
						arr[i] = item.specs_id // 每一项规格组合
						let result = specsPrice.find((itm) => itm.specs_ids == arr.sort((a, b) => a - b)
							.toString())
						item.state = result ? true : false
					})
				} else {
					this.specs_ids = [...this.specs_ids]
				}
			},
			handleSubmit(type) {
				if (this.specsList.length) {
					let empty = this.specs_ids.findIndex((item) => !item)
					if (empty > -1) return this.$Toast('请选择规格')
				}
				if (this.v_input > this.stock) return this.$Toast('库存不足')

				// 立即购买
				if (type == 2) {
					let params = `?goods_id=${this.pageData.goods_id}&goods_num=${this.v_input}`
					if (this.specsList.length) params =
						`${params}&specs_bind_id=${this.currentSpecs.id}&specs_bind_text=${this.currentSpecs.specs_title}`
					this.toUrl('/orderPage/order/createOrders' + params)
					return
				}

				// 加入购物车
				this.$http.post({
					url: '/zzj_singleSaleApi/joinCart',
					data: {
						num: this.v_input,
						specs_bind_id: this.currentSpecs.id || '',
						specs_bind_text: this.currentSpecs.specs_title || '',
						goods_id: this.pageData.goods_id,
						shop_id: this.pageData.store_id || ''
					}
				}).then((res) => {
					if (res.errcode != 100) return this.$Toast(res.msg)
					this.close()
					this.$Toast('加入购物车成功')
					this.$emit('getCart')
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.specsPop {
		.img {
			width: 168rpx;
			height: 168rpx;
		}

		.specsItm {
			background: #f4f4f4;
			border: 2rpx solid #f4f4f4;
			padding: 8rpx 36rpx;
			margin: 0 20rpx 20rpx 0;

			&.active {
				background: #fff0f0;
				border: 2rpx solid #ff4b4e;
				color: #ff4b4e;
			}
		}

		.btn {
			margin-bottom: constant(safe-area-inset-bottom);
			margin-bottom: env(safe-area-inset-bottom);
			flex: 1;
			height: 72rpx;
			border-radius: 36rpx;
		}
	}
</style>